<?php
class fotoedit_block extends SClass {

    public function process() {
        try{
            $key = $this->getValue('key');
            $this->setValue('key', $key);
            $objectid = $this->getValue('objectid');
            PackageLoader::Get()->import('JSFileUploadPreviewer');
            $imageToDelete = $this->getArgumentSecure('imageToDelete');//если пришла строка какие фотки удалить
            if($imageToDelete) {
                if($key == 'photoalbum') {
                    Triumph::Get()->getMediaService()->deletePhoto($objectid,$imageToDelete);
                }

                // редирект на эту же страницу без учёта параметра удаления
                $url = Engine_URLParser::Get()->getCurrentURL();
                $end = strstr($url,'?imageToDelete=');
                $url = str_replace($end,'',$url);
                header("Location: " .$url);
            }
            $button = $this->getArgumentSecure('button');
            $files = $this->getControlValue('files');
            $names = (array)$this->getControlValue('files_names');
            if ($button) {
                try {
                    foreach ($files['tmp_name'] as $k => $v) {
                        if($key == 'photoalbum') {
                            Triumph::Get()->getMediaService()->addTriumphImage(
                                $objectid,
                                @$names[$k],
                                $v
                            );
                        }
                    }
                    $this->setValue('message', 'ok');
                } catch (ServiceUtils_Exception $e) {
                    $this->setValue('AErrors', $e->getErrors());
                }
            }
            if($key == 'photoalbum') {
                $foto = Triumph::Get()->getMediaService()->getPhotoByAlbumId($objectid);
            }
            $this->setValue('AFoto', $this->_makeFotoArray($foto));
            $this->setValue('currentUrl', Engine_URLParser::Get()->getCurrentURL());
            $this->setValue('key', $key);

        }catch(Exception $e){}
    }

    private function _makeFotoArray($z) {
        $arr = array();
        while ($x = $z->getNext()) {
            try {
                $arr[] = array(
                    'id' => $x->getId(),
                    'comment' => $x->getDescription(),
                    'image' => $x->makeImageThumb(200,150,'cut')
                );
            } catch (Exception $e) {

            }
        }
        return $arr;
    }

}